/**
 * 				Watcher.java
 *				------------
 *		
 *   Author:	bin04017
 *   ID:		bin04017
 *	 Created:	24.01.2007
 *	 Project:	Mochito
 *	 Package:	tools.watcher
 *	 Usage:		
 */package mochito.tools.serverPackage.watcher;
import java.io.IOException;
import java.net.ServerSocket;

import mochito.tools.properties.PropertieReader;
import mochito.tools.serverPackage.server.Server;
import mochito.tools.serverPackage.systray.ServerSystray;


/**
 * 				Watcher.java
 *				------------
 *		
 *   Author:	Moser Dominik
 *   ID:		bin04017
 *	 Created:	24.01.2007
 *	 Project:	Mochito
 *	 Package:	
 *	 Usage:		
 */

/**
 * @author bin04017
 *
 */
public class Watcher implements Runnable {

	private ServerSystray serverSystray = null;
	
	private boolean running = true;
	
	private Thread thread = null;

	private Integer port = PropertieReader.getPort();

	private Server server = null;
	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	public Watcher(ServerSystray serverSystray){
		this.serverSystray = serverSystray;
	}
	
	public Watcher(ServerSystray serverSystray, Integer port){
		this.serverSystray = serverSystray;
		this.port = port;
	}
	
	public void run() {
		while(running){
			if((serverSystray == null)||(serverSystray != null && serverSystray.getRunning())){
				try {
					if (server == null) {
						server = new Server((new ServerSocket(this.port)));
						thread = new Thread(server);
						thread.start();
					}					
				} catch (IOException e) {
					e.printStackTrace();
				}
			}else {
				if(thread != null){
					server.stop();
					server = null;
					thread = null;
				}
			}
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @return the running
	 */
	public boolean isRunning() {
		return running;
	}

	/**
	 * @param running the running to set
	 */
	private void setRunning(boolean running) {
		this.running = running;
	}
	public void stop(){
		setRunning(false);
	}

}
